//
//  XZLeaveApplyVC.m
//  Teecloud
//
//  Created by PC on 2018/11/5.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZLeaveApplyVC.h"
#import "XZchooseAssessingVC.h"

#import "FSTextView.h"
#import "GMPhotoCell.h"
#import "TZImagePickerController.h"
#import <KSPhotoBrowser/KSPhotoBrowser.h>
#import "ZJPickBaseView.h"
#import "ZJDatePickerView.h"
#import "ZJNormalPickerView.h"

#import "GMFileModel.h"
#import "XZAcceptUsers.h"
@interface XZLeaveApplyVC ()<UICollectionViewDataSource,UICollectionViewDelegate,XMGWaterflowLayoutDelegate,TZImagePickerControllerDelegate,UITextViewDelegate>
//类型
@property (weak, nonatomic) IBOutlet UILabel *typeNameLabel;
//开始时间
@property (weak, nonatomic) IBOutlet UILabel *startDateLabel;
//结束时间
@property (weak, nonatomic) IBOutlet UILabel *endDateLabel;
@property (weak, nonatomic) IBOutlet UILabel *numberLabel;
//文本输入框
@property (weak, nonatomic) IBOutlet FSTextView *textView;

//选择图片的view
@property (weak, nonatomic) IBOutlet UIView *bagView;

@property (nonatomic, strong) UICollectionView *collectionView;
/**本地图片数组*/
@property (nonatomic, strong) NSMutableArray *imgArr;
@property (nonatomic, strong) NSMutableArray *netImgArr;
//最多个数选择图片
@property(nonatomic,assign)NSInteger maxCount;
//审批人员
@property (nonatomic, copy) NSArray *pepoleNumArray;
//请假类型
@property (nonatomic, assign) NSInteger selectIndex;

@end

@implementation XZLeaveApplyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"请假申请";
    self.view.backgroundColor = kWhiteColor;
    self.maxCount = 5;/**设置最大图片数量*/
    [self.collectionView registerNib:[UINib nibWithNibName:@"GMPhotoCell" bundle:nil] forCellWithReuseIdentifier:@"GMPhotoCell"];
    [self setTextView];
}
- (void)setTextView{
    //设置FSTextView的属性
    _textView.placeholder = @"不得少于8个字";
    _textView.placeholderColor = [UIColor colorWithHexString:@"8C8C8C" andAlpha:1.0];
    _textView.placeholderFont = [UIFont systemFontOfSize:14];
    _textView.canPerformAction = NO;
    _textView.delegate = self;
    _textView.textColor = kDarkGrayColor;
    _textView.backgroundColor = kWhiteColor;
    _textView.tintColor = kDarkGrayColor;
    _textView.layer.borderWidth = 0.5;
    _textView.layer.borderColor = [UIColor colorWithHexString:@"8C8C8C" andAlpha:1.0].CGColor;
    _textView.maxLength = 200;//限制输入最大字符数.
}
//请假类型
- (IBAction)applyTypeTapAction:(UITapGestureRecognizer *)sender {
    NSMutableArray *array = [NSMutableArray array];
    [array addObjectsFromArray:@[@"病假",@"事假",@"婚假",@"丧假",@"产假",@"年假"]];
    kWeakObject(self)
    [ZJNormalPickerView zj_showStringPickerWithTitle:@"" dataSource:array defaultSelValue:nil isAutoSelect: YES rowHeight:40 lineColor:kDarkGrayColor confirmBtnTitleColor:kDarkGrayColor cancelBtnTitleColor:kDarkGrayColor selecteRowTextColor:kDarkGrayColor selectRowBGColor:kWhiteColor leftBtnTitle:@"取消" rightBtnTitle:@"确定" resultBlock:^(id selectValue, NSInteger index) {
        weakself.selectIndex = index + 1;
        weakself.typeNameLabel.text = array[index];
    } cancelBlock:^{
        
    }];
}
//开始时间
- (IBAction)starDateTapAction:(UITapGestureRecognizer *)sender {
    kWeakObject(self)
    [ZJDatePickerView zj_showDatePickerWithTitle:@"请选择开始时间" dateType:ZJDatePickerModeYMDHM defaultSelValue:nil minDate:nil maxDate:nil isAutoSelect:YES lineColor:kDarkGrayColor rowHeight:40 resultBlock:^(NSString *selectValue) {
        weakself.startDateLabel.text = selectValue;
    } cancelBlock:^{
        
    }];
    
}
//结束时间
- (IBAction)endDateTapAction:(UITapGestureRecognizer *)sender {
    kWeakObject(self)
    [ZJDatePickerView zj_showDatePickerWithTitle:@"请选择结束时间" dateType:ZJDatePickerModeYMDHM defaultSelValue:nil minDate:nil maxDate:nil isAutoSelect:YES lineColor:kDarkGrayColor rowHeight:40 resultBlock:^(NSString *selectValue) {
        weakself.endDateLabel.text = selectValue;
    } cancelBlock:^{
        
    }];
}
//选择审批人员
- (IBAction)chooseAssessingOfficerTapAction:(UITapGestureRecognizer *)sender {
    XZchooseAssessingVC *assessingVC = [[XZchooseAssessingVC alloc] init];
    assessingVC.AcceptUsers = self.model.AcceptUsers;
    kWeakObject(self)
    assessingVC.ChooseAssesseBlock = ^(NSArray * _Nonnull selectArray) {
        weakself.pepoleNumArray = selectArray;
        NSString *name = @"";
        for (XZAcceptUsers *model in selectArray) {
            name = [NSString stringWithFormat:@"%@ %@ ",name,model.Name];
        }
        self.numberLabel.text = name;
    };
    [self.navigationController presentSemiViewController:assessingVC withOptions:@{
                                                                                   KNSemiModalOptionKeys.pushParentBack    : @(NO),
                                                                                   KNSemiModalOptionKeys.animationDuration : @(0.5),
                                                                                   KNSemiModalOptionKeys.shadowOpacity     : @(0.3)
                                                                                   }];
}
- (NSMutableArray *)netImgArr{
    if (!_netImgArr) {
        _netImgArr = [[NSMutableArray alloc]init];
    }
    return _netImgArr;
}
-(NSMutableArray *)imgArr{
    if (!_imgArr) {
        _imgArr = [[NSMutableArray alloc] init];
    }
    return _imgArr;
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        //1.初始化layout
        // 创建布局
        XMGWaterflowLayout *layout = [[XMGWaterflowLayout alloc] init];
        layout.delegate = self;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH-20, 80) collectionViewLayout:layout];
        _collectionView.backgroundColor = kWhiteColor;
        _collectionView.dataSource = self;
        _collectionView.scrollEnabled = NO;
        _collectionView.delegate = self;
        [self.bagView addSubview:_collectionView];
        
    }
    return _collectionView;
}
//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.imgArr.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GMPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GMPhotoCell" forIndexPath:indexPath];
    if (indexPath.row == self.imgArr.count || self.imgArr.count == 0) {
        cell.photoImg.image = [UIImage imageNamed:@"photo_add"];
        cell.delectBtn.hidden=YES;
    }else{
        cell.photoImg.image =self.imgArr[indexPath.row];
        cell.delectBtn.hidden=NO;
        cell.delectBtn.tag = indexPath.row +1000;
        [cell.delectBtn addTarget:self action:@selector(delectImageWithBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return cell;
}
#pragma mark - <XMGWaterflowLayoutDelegate>
- (CGFloat)waterflowLayout:(XMGWaterflowLayout *)waterflowLayout heightForItemAtIndex:(NSUInteger)index itemWidth:(CGFloat)itemWidth{
    //计算item的高度
    return itemWidth;
}

- (CGFloat)rowMarginInWaterflowLayout:(XMGWaterflowLayout *)waterflowLayout{
    return 10;
}
/**返回每行的个数*/
- (CGFloat)columnCountInWaterflowLayout:(XMGWaterflowLayout *)waterflowLayout{
    return 5;
}

- (UIEdgeInsets)edgeInsetsInWaterflowLayout:(XMGWaterflowLayout *)waterflowLayout{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if (indexPath.row == self.imgArr.count) {
        
        //显示弹出框列表选择
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                       message:nil
                                                                preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
                                                                 //响应事件
                                                                 NSLog(@"action = %@", action);
                                                             }];
        UIAlertAction* photoAlbum = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault
                                                            handler:^(UIAlertAction * action) {
                                                                //响应事件
                                                                TZImagePickerController *pickerController = [[TZImagePickerController alloc]initWithMaxImagesCount:self.maxCount - self.imgArr.count delegate:self];
                                                                pickerController.sortAscendingByModificationDate = NO;
                                                                kWeakObject(self)
                                                                [pickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photo, NSArray *assets, BOOL isSelectOriginalPhoto){
                                                                    
                                                                    if (photo.count) {
                                                                        [weakself addNewImages:photo];
                                                                    }
                                                                }];
                                                                [self presentViewController:pickerController animated:YES completion:nil];
                                                            }];
        [alert addAction:cancelAction];
        [alert addAction:photoAlbum];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else{
        /**放大图片*/
        GMPhotoCell * cell = (GMPhotoCell *)[self collectionView:collectionView cellForItemAtIndexPath:indexPath];//即为要得到的cell
        NSMutableArray *items = @[].mutableCopy;
        NSInteger count = self.imgArr.count;
        for (int i = 0; i < count; i++) {
            UIImageView *imgV = cell.photoImg;
            KSPhotoItem *item = [KSPhotoItem itemWithSourceView:imgV image:self.imgArr[i]];
            [items addObject:item];
        }
        
        KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:items selectedIndex:indexPath.row];
        browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleRotation;
        browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlurPhoto;
        browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
        browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
        browser.bounces = NO;
        [browser showFromViewController:self];
    }
    
    
}
//添加多张图片--
-(void)addNewImages:(NSArray *)newImages{
    
    //默认多张图片选择顺序是按照用户选择顺序，所以这里进行反序，因为后面把刚添加的index 置为0；
    NSArray* images = [[newImages reverseObjectEnumerator] allObjects];
    [images enumerateObjectsUsingBlock:^(UIImage * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.imgArr insertObject:obj atIndex:0];
        
    }];
    [self.collectionView reloadData];
    //先从服务器获取OSS需要的数据
    
}
#pragma mark --- <UIImagePickerControllerDelegate>
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *image = info[@"UIImagePickerControllerOriginalImage"];
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (image) {
        [self addNewImage:image];
    }
}
-(void)addNewImage:(UIImage *)newImage{
    
    [self.imgArr insertObject:newImage atIndex:0];
    [self.collectionView reloadData];
    
}
- (void)delectImageWithBtn:(UIButton *)sender{
    NSInteger index =sender.tag -1000;
    [self.imgArr removeObjectAtIndex:index];
    [self.collectionView reloadData];
}
//提交
- (IBAction)confirmButtonAction:(UIButton *)sender {
    if ([self.typeNameLabel.text isEqualToString:@"请选择"]) {
        [MBProgressHUD showErrorOrSuc:@"请选择请假类型" toView:self.view];
        return;
    }
    if ([self.startDateLabel.text isEqualToString:@"请选择"]) {
        [MBProgressHUD showErrorOrSuc:@"请选择开始时间" toView:self.view];
        return;
    }
    if ([self.endDateLabel.text isEqualToString:@"请选择"]) {
        [MBProgressHUD showErrorOrSuc:@"请选择结束时间" toView:self.view];
        return;
    }
    
    if (self.textView.text.length < 8) {
        [MBProgressHUD showErrorOrSuc:@"请假事由不得少于8个字" toView:self.view];
        return;
    }
    if (self.pepoleNumArray == nil) {
        [MBProgressHUD showErrorOrSuc:@"请选择审批人员" toView:self.view];
        return;
    }
    
    //有图片的话先上传图片
    dispatch_group_t uploadGroup = dispatch_group_create();
    for (NSInteger i =0; i<self.imgArr.count; i++) {
        dispatch_group_enter(uploadGroup);
        NSDictionary *dict= @{@"from":FROM_IOS,
                              @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                              @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                              @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                              @"fileType":@"res-remark"
                              };
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        NSData *imageData = UIImageJPEGRepresentation(self.imgArr[i], 0.5);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
        [HJNetwork uploadImageURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=UploadFile&$v=%@",VERSION] parameters:dict imageData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg" progress:^(NSProgress *progress) {
            
        } callback:^(id responseObject, NSError *error) {
            if (!error) {
                if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]){
                    GMFileModel *model = [GMFileModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                    [self.netImgArr addObject:model];
                    dispatch_group_leave(uploadGroup);
                }else{
                    /**显示错误信息*/
                    [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
                }
            }
        }];
    }
    dispatch_group_notify(uploadGroup, dispatch_get_main_queue(), ^{
        [self sumbitAllData];
    });
}
//提交
- (void)sumbitAllData{
    NSString *imgFile1Id =@"";
    NSString *imgFile2Id =@"";
    NSString *imgFile3Id =@"";
    NSString *imgFile4Id =@"";
    NSString *imgFile5Id =@"";
    for (NSInteger i=0; i<self.netImgArr.count; i++) {
        GMFileModel *model =self.netImgArr[i];
        switch (i) {
            case 0:{
                imgFile1Id =model.Id;
            }
                break;
            case 1:{
                imgFile2Id =model.Id;
            }
                break;
            case 2:{
                imgFile3Id =model.Id;
            }
                break;
            case 3:{
                imgFile4Id =model.Id;
            }
                break;
            case 4:{
                imgFile5Id =model.Id;
            }
                break;
                
            default:
                break;
        }
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:@(self.selectIndex) forKey:@"leaveType"];
    [dict setValue:self.startDateLabel.text forKey:@"startTime"];
    [dict setValue:self.endDateLabel.text forKey:@"endTime"];
    [dict setValue:self.textView.text forKey:@"content"];
    //图片
    [dict setValue:imgFile1Id forKey:@"imgFile1Id"];
    [dict setValue:imgFile2Id forKey:@"imgFile2Id"];
    [dict setValue:imgFile3Id forKey:@"imgFile3Id"];
    [dict setValue:imgFile4Id forKey:@"imgFile4Id"];
    [dict setValue:imgFile5Id forKey:@"imgFile5Id"];
    //审批人员
    NSMutableArray *tempArray = [[NSMutableArray alloc]init];
    for (XZAcceptUsers *model in self.pepoleNumArray) {
        [tempArray addObject:model.Id];
    }
    NSString *jsonString = tempArray.mj_JSONString;
    
    [dict setValue:jsonString forKey:@"auditUserIds"];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=PostLeaveApply&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSString *msg = [responseObject objectForKey:RESULT_NAME_Message];
                if (!msg) {
                    [MBProgressHUD showErrorOrSuc:@"提交成功" toView:self.view];
                }else{
                    [MBProgressHUD showErrorOrSuc:msg toView:self.view];
                }
                
                [self.navigationController popViewControllerAnimated:true];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络出错" toView:self.view];
        }
    }];
}
@end
